package com.version1_4.service.implement;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.util.aliyun.OCSutils;
import com.util.format.ReevesMap;
import com.util.format.TimeFormat;
import com.version1_4.dao.FeedDao;
import com.version1_4.dao.TopicDao;
import com.version1_4.service.TopicService;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by reeveslee on 16/4/27.
 */
@Service
public class TopicServiceImpl implements TopicService {
    private static final Logger LOGGER = Logger.getLogger(TopicServiceImpl.class);

    @Autowired
    private TopicDao topicDao;

    @Autowired
    private FeedDao feedDao;

    /**
     * 话题主页面
     *
     * @param lastId
     * @return
     */
    @Override
    public String topicMainPage(int lastId) {
        ReevesMap result = new ReevesMap();
        if (lastId == 0) {
            List<Map<String, Object>> banners = topicDao.getBanner();
            for (Map<String, Object> banner : banners) {
                String imgSrc = (String) banner.get("img") + "@!halfHeight";
                imgSrc = imgSrc.replace("kuibutech.oss-cn-shanghai.aliyuncs.com", "pic.kuibutech.com");
                banner.replace("img", imgSrc);
            }
            result.put("banner", banners);
        }

        List<Map<String, Object>> topicList = topicDao.topicPage(lastId);
        for (Map<String, Object> topicItem : topicList) {
            String imageSrc = (String) topicItem.get("image") + "@!equalHeight";
            imageSrc = imageSrc.replace("kuibutech.oss-cn-shanghai.aliyuncs.com", "pic.kuibutech.com");
            topicItem.replace("image", imageSrc);
        }
        result.put("topic", topicList);
        return result.toJsonString();
    }

    /**
     * 话题评论界面
     *
     * @param topicId
     * @param lastId
     * @return
     */
    @Override
    public String feed(int userId, int topicId, int lastId) {
        ReevesMap result = new ReevesMap();
        Map<String, Object> topicInfo = topicDao.topicInfo(topicId);
        boolean invitePraise = false;

        if (topicInfo == null) {
            result.setCode(500);
            result.setInfo("No Such Topic ID");
        } else {
            result.setCode(200);
            if (lastId == 0) {
                String titleImg = (String) topicInfo.get("img") + "@!13To10Height";
                titleImg = titleImg.replace("kuibutech.oss-cn-shanghai.aliyuncs.com", "pic.kuibutech.com");
                result.put("img", titleImg);
                result.put("title", topicInfo.get("title"));
                result.put("secondary", topicInfo.get("secondary"));
                result.put("feedCount", topicDao.feedCount(topicId));
                result.put("userCount", topicDao.userCount(topicId));

                boolean isFollow = topicDao.follow(topicId, userId);
                if (isFollow) {
                    result.put("state", "following");
                } else {
                    result.put("state", "unfollowing");
                }

                result.put("sponsor", topicDao.sponsor((int) topicInfo.get("sponsorId")));

                Map<String, Object> invite = topicDao.invite(topicId);

                if (invite != null) {
                    invite.replace("image", JSONArray.parse((String) invite.get("image")));
                    invite.replace("voice", JSONObject.parse((String) invite.get("voice")));
                    invite.replace("time", TimeFormat.convertTimeToFormat(((Date) invite.get("time")).getTime() / 1000));
                    invitePraise = topicDao.hasPraised(userId, (int) ((long) invite.get("id")));
                    invite.put("isPraised", invitePraise);

                }

                result.put("invite", invite);
                result.put("feedsType", "hot");

                List<Map<String, Object>> feeds = topicDao.feeds(topicId, lastId);
                for (Map<String, Object> feed : feeds) {
                    feed.replace("image", JSONArray.parse((String) feed.get("image")));
                    feed.replace("voice", JSONObject.parse((String) feed.get("voice")));
                    feed.replace("time", TimeFormat.convertTimeToFormat(((Date) feed.get("time")).getTime() / 1000));
                    feed.put("isPraised", topicDao.hasPraised(userId, (int) ((long) feed.get("id"))));
                }

                result.put("feeds", feeds);

            } else {
                result.put("feedsType", "hot");
                List<Map<String, Object>> feeds = topicDao.feeds(topicId, lastId);
                for (Map<String, Object> feed : feeds) {
                    feed.replace("image", JSONArray.parse((String) feed.get("image")));
                    feed.replace("voice", JSONObject.parse((String) feed.get("voice")));
                    feed.replace("time", TimeFormat.convertTimeToFormat(((Date) feed.get("time")).getTime() / 1000));
                    feed.put("isPraised", topicDao.hasPraised(userId, (int) ((long) feed.get("id"))));
                }

                result.put("feeds", feeds);
            }
        }

        return result.toJsonString();
    }

    /**
     * 话题评论 -最新排序 -只有评论内容
     *
     * @param topicId
     * @param lastId
     * @return
     */
    @Override
    public String newFeed(int topicId, int lastId, int userId) {
        ReevesMap result = new ReevesMap();
        result.put("feedsType", "new");
        result.put("feedCount", topicDao.feedCount(topicId));
        result.put("userCount", topicDao.userCount(topicId));
        List<Map<String, Object>> feeds = topicDao.newFeeds(topicId, lastId);
        for (Map<String, Object> feed : feeds) {
            feed.replace("image", JSONArray.parse((String) feed.get("image")));
            feed.replace("voice", JSONObject.parse((String) feed.get("voice")));
            feed.replace("time", TimeFormat.convertTimeToFormat(((Date) feed.get("time")).getTime() / 1000));
            feed.put("isPraised", topicDao.hasPraised(userId, (int) ((long) feed.get("id"))));
        }

        result.put("feeds", feeds);
        return result.toJsonString();
    }

    /**
     * 追踪界面
     *
     * @param userId
     * @return
     */
    @Override
    public String follow(int userId) {
        ReevesMap reevesMap = new ReevesMap(); // 结果Map
        List<Map<String, Object>> followTopicIds = topicDao.followTopicId(userId);
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> followItem : followTopicIds) {
            Map<String, Object> itemMap = new LinkedMap();
            int topicId = (int) followItem.get("topicId");
            Map<String, Object> topicInfo = topicDao.topicInfo(topicId);
            List<Map<String, Object>> newestFeeds = feedDao.newestFeed(topicId);
            for (Map<String, Object> newestFeed : newestFeeds) {
                newestFeed.replace("image", JSONArray.parse((String) newestFeed.get("image")));
                newestFeed.replace("voice", JSONObject.parse((String) newestFeed.get("voice")));
                newestFeed.replace("time", TimeFormat.convertTimeToFormat(((Date) newestFeed.get("time")).getTime() / 1000));
            }
            int newFeedNum = feedDao.newFeedNum(topicId, (Date) followItem.get("time"));
            itemMap.put("topicId", topicId);
            itemMap.put("tag", topicInfo.get("tag"));
            itemMap.put("image", ((String)topicInfo.get("img")).replace("kuibutech.oss-cn-shanghai.aliyuncs.com", "pic.kuibutech.com")+"@!16To9Height");
            itemMap.put("title", topicInfo.get("title"));
            itemMap.put("newFeedNum", newFeedNum);
            itemMap.put("feeds", newestFeeds);
            result.add(itemMap);
        }

        reevesMap.put("result", result);
        return net.sf.json.JSONObject.fromObject(reevesMap).toString();
    }

    /**
     * 追踪话题
     *
     * @param userId
     * @param topicId
     * @return
     */
    @Override
    public String addFollow(int userId, int topicId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = topicDao.addFollow(userId, topicId);
        if (result == false) {
            reevesMap.setInfo("Already Has Follow The Topic.");
        }
        reevesMap.put("result", result);
        return net.sf.json.JSONObject.fromObject(reevesMap).toString();
    }

    /**
     * 取消追踪
     *
     * @param userId
     * @param topicId
     * @return
     */
    @Override
    public String removeFollow(int userId, int topicId) {
        ReevesMap reevesMap = new ReevesMap();
        boolean result = topicDao.removeFollow(userId, topicId);
        if (result == false) {
            reevesMap.setInfo("No Record Found With UserId And TopicId Given");
        }
        reevesMap.put("result", topicDao.removeFollow(userId, topicId));
        return net.sf.json.JSONObject.fromObject(reevesMap).toString();
    }

    /**
     * 话题搜索
     *
     * @param key
     * @return
     */
    @Override
    public String search(String key) {
        ReevesMap reevesMap = new ReevesMap();
        List<Map<String, Object>> searchList = topicDao.search(key);
        if (searchList == null) {
            reevesMap.setCode(500);
            reevesMap.setInfo("No More Data");
        } else {
            for (Map<String, Object> searchItem : searchList) {
                searchItem.replace("image", ((String) searchItem.get("image") + "@!equalHeight").replace("kuibutech.oss-cn-shanghai.aliyuncs.com", "pic.kuibutech.com"));
                searchItem.replace("time", TimeFormat.monthDayHourMin(((Date) searchItem.get("time")).getTime()));
                searchItem.put("key", key);
            }
        }

        reevesMap.put("result", searchList);
        return reevesMap.toJsonString();
    }

    /**
     * 话题标签界面
     *
     * @param name
     * @param lastId
     * @return
     */
    @Override
    public String tag(String name, int lastId) {
        ReevesMap reevesMap = new ReevesMap();
        List<Map<String, Object>> result = topicDao.tag(name, lastId);
        Map<String, Object> tagInfo = topicDao.tagInfo(name);
        reevesMap.put("banner", tagInfo.get("banner"));
        if (result == null) {
            reevesMap.setCode(500);
            reevesMap.setInfo("No More Data");
        } else {
            for (Map<String, Object> item : result) {
                item.replace("image", ((String) item.get("image") + "@!equalHeight").replace("kuibutech.oss-cn-shanghai.aliyuncs.com", "pic.kuibutech.com"));
                item.replace("time", TimeFormat.yearMonthDay(((Date) item.get("time")).getTime()));
            }
        }
        reevesMap.put("result", result);
        return reevesMap.toJsonString();
    }

    /**
     * 推荐标签
     *
     * @return
     */
    @Override
    public String recomTag() {
        ReevesMap reevesMap = new ReevesMap();
        List<Map<String, Object>> recomTagList = topicDao.recomTag();
        if (recomTagList == null) {
            reevesMap.setCode(500);
            reevesMap.setInfo("No More Data");
        }
        reevesMap.put("result", recomTagList);
        return reevesMap.toJsonString();
    }
}
